package parsers;

import common.ParamStorage;
import java.rmi.RemoteException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.ejb.CreateException;
import javax.naming.NamingException;
import presentation.CurrencyElement;
import presentation.DateElement;
import presentation.EmailElement;
import presentation.LinkElement;
import presentation.PhoneElement;
import presentation.PresentationElement;
import presentation.TextElement;
import templates.PresentationTemplate;

public class InputParser {
    private String output;
    private ParamStorage storage;

    public InputParser(ParamStorage storage) {
        this.storage = storage;
        output = "";
    }

    public String parse(PresentationElement e) {
        e.acceptInput(this);
        return output;
    }

    public void parseText(TextElement e) {
        PresentationTemplate pt = e.getTemplate();
        if (storage.hasParam("edit" + pt.getAlias())) {
            output = storage.getParam("edit" + pt.getAlias());
        }
    }

    public void parsePhone(PhoneElement e) {
        PresentationTemplate pt = e.getTemplate();
        if (storage.hasParam("edit" + pt.getAlias())) {
            output = storage.getParam("edit" + pt.getAlias());
        }
    }

    public void parseEmail(EmailElement e) {
        PresentationTemplate pt = e.getTemplate();
        if (storage.hasParam("edit" + pt.getAlias())) {
            output = storage.getParam("edit" + pt.getAlias());
        }
    }

    public void parseLink(LinkElement e) {
        PresentationTemplate pt = e.getTemplate();
        if (storage.hasParam("edit" + pt.getAlias())) {
            output = storage.getParam("edit" + pt.getAlias());
        }
    }

    public void parseCurrency(CurrencyElement e) {
        PresentationTemplate pt = e.getTemplate();
        if (storage.hasParam("edit" + pt.getAlias())) {
            output = storage.getParam("edit" + pt.getAlias());
        }
    }

    public void parseDate(DateElement e) {
        PresentationTemplate pt = e.getTemplate();
        Calendar c = Calendar.getInstance();
        if (storage.hasParam(pt.getAlias() + "day")) {
            c.set(Calendar.DAY_OF_MONTH, Integer.parseInt(storage.getParam(pt.getAlias() + "day")));
        }
        if (storage.hasParam(pt.getAlias() + "month")) {
            c.set(Calendar.MONTH, Integer.parseInt(storage.getParam(pt.getAlias() + "month"))-1);
        }
        if (storage.hasParam(pt.getAlias() + "year")) {
            c.set(Calendar.YEAR, Integer.parseInt(storage.getParam(pt.getAlias() + "year")));
        }
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        Date d = c.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
        output = sdf.format(d);
    }
}
